﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronPython;
using IronPython.Hosting;

namespace Dungeon_Dive
{
    class PythonEngine
    {
        private ScriptEngine scriptEngine;
        private ScriptScope scriptScope;
        private Dictionary<String, CompiledCode> scripts;

        public PythonEngine()
        {
            scriptEngine = Python.CreateEngine();
            List<String> searchPaths = new List<string>();
            searchPaths.Add(".\\PyLib");
            scriptEngine.SetSearchPaths(searchPaths);
            scriptScope = scriptEngine.CreateScope();
            scripts = new Dictionary<String, CompiledCode>();

            //Basic imports
            scriptEngine.Execute("import clr", scriptScope);
            scriptEngine.Execute("clr.AddReference(\"System\")", scriptScope);
            scriptEngine.Execute("from System import *", scriptScope);
            scriptEngine.Execute("clr.AddReference(\"Microsoft.Xna.Framework\")", scriptScope);
            scriptEngine.Execute("from Microsoft.Xna.Framework import *", scriptScope);
        }

        public void AddScriptFromFile(String name, String fileName)
        {
            ScriptSource source = scriptEngine.CreateScriptSourceFromFile(fileName);
            if (!scripts.ContainsKey(name)) scripts.Add(name, source.Compile());
        }

        public void AddScriptFromString(String name, String code)
        {
            ScriptSource source = scriptEngine.CreateScriptSourceFromString(code);
            scripts.Add(name, source.Compile());
        }

        public void SetVariable(String name, Object variable)
        {
            scriptScope.SetVariable(name, variable);
        }

        public Object GetVariable(String name)
        {
            return scriptScope.GetVariable(name);
        }

        public void RunScript(String name)
        {
            scripts[name].Execute(scriptScope);
        }

        public void RunScriptFromString(String script)
        {
            scriptEngine.Execute(script, scriptScope);
        }
    }
}
